'use client';

import { secuApi } from '@/state/api';
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { useRef } from 'react';
import { Provider, useDispatch, useSelector, useStore } from 'react-redux';

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes();
export const useAppSelector = useSelector.withTypes();
export const useAppStore = useStore.withTypes();

const rootReducer = combineReducers({
    [secuApi.reducerPath]: secuApi.reducer
});

const makeStore = () => {
    const store = configureStore({
        reducer: rootReducer,
        middleware: (getDefaultMiddleware) =>
            getDefaultMiddleware().concat(secuApi.middleware)
    });
    return store;
};

export const StoreProvider = ({ children }) => {
    const storeRef = useRef(null);
    if (!storeRef.current) {
        // Create the store instance the first time this renders
        storeRef.current = makeStore();
    }

    return <Provider store={storeRef.current}>{children}</Provider>;
};
